import { goToPageRule, moduleTypeRule, objectAny } from "../options/base";


export function goToBack(
	delta: number | undefined = 1
): Promise<UniApp.NavigateBackOptions | undefined> {
	return new Promise((resolve, reject) => {
		uni.navigateBack({
			delta,
			success: resolve,
			fail: reject
		})
	})

}

export function goToPage(
	navOptions: goToPageRule,
	clearLocal:undefined|boolean=false
): Promise<void> {
	return new Promise((resolve, reject) => {
		const toggle: {
			push: `navigateTo`,
			pushTab: `switchTab`,
			replaceAll: `reLaunch`,
			replace: `redirectTo`
		} = {
			push: `navigateTo`,
			pushTab: `switchTab`,
			replaceAll: `reLaunch`,
			replace: `redirectTo`
		};
		const type = toggle[navOptions.navType];
		const haveParams=navOptions.path.includes(`?`)
		let goToUrl=navOptions.path+objectToQuery(navOptions.params)
		// 已经有参数了 那么我们就直接拼接参数 不用带？
		if(haveParams){
			goToUrl=navOptions.path+`&`+objectToQuery(navOptions.params).substring(1)
		}

		uni[type]({
			url:goToUrl,
			success: () => {
				resolve();
			},
			fail: reject,
			complete:()=>{
				if(clearLocal){
					uni.removeStorageSync(`uni_id_token`);
					uni.removeStorageSync(`uni_id_token_expired`)
				}
			}
		})
	})
}
/**
 * 根据订单数据的详细信息 跳转到合适的页面
 * @param {object} orderInfo - 订单详细数据
 * @param {moduleTypeRule} moduleName  - 模块名称
 */
export function orderNavToRightPage(
	orderInfo:objectAny,
	moduleName:moduleTypeRule
){
	const  options={
		//默认设置为开启 因为在 foodTakeout 模块下 menu_status 不是实时更新的
		menu_status:true,   
		nav_path:``,
		_id:``,
	};
	let menuId=``;
	if(moduleName==='foodTakeout'){
		options.nav_path=`/microModule/foodTakeout/pages/foodStore/foodStore`
		options._id=orderInfo.merchant_id  //商户ID
		if(options._id==null){
			options._id=orderInfo.product_list[0]._id		//商户ID
		}

		menuId=`&menuId=${orderInfo.menu_id[0]._id}` // 模块ID
	}else if(moduleName===`runErrand`){
		options.nav_path=orderInfo.menu_id[0].nav_path;
		options._id=orderInfo.menu_id[0]._id;      //模块ID
	}
	const { nav_path,_id } = options
	let navPath=nav_path;

	if(nav_path.includes(`?`)){
        // 如果未包含ID 那么我们就添加id参数
        if(!/(\?id=)|(\&id=)/.test(nav_path)){
            navPath=nav_path+`&id=${_id}&menuId=${moduleName}`
        }
    }else{
        navPath=nav_path+`?id=${_id}&menuId=${moduleName}`
    }
    goToPage({
        path: navPath,
        navType: `push`
    })
}


export function objectToQuery(argument1: any, argument2?: any) {
	let obj = arguments[0];
	let prefix = arguments[1];
	if (typeof obj !== "object") return "";
	const attrs = Object.keys(obj);
	return attrs.reduce((query, attr, index) => {
		// 判断是否是第一层第一个循环
		if (index === 0 && !prefix) query += "?";
		if (typeof obj[attr] === "object") {
			const subPrefix = prefix ? `${prefix}[${attr}]` : attr;
			query += objectToQuery(obj[attr], subPrefix);
		} else {
			if (prefix) {
				query += `${prefix}[${attr}]=${obj[attr]}`;
			} else {
				query += `${attr}=${obj[attr]}`;
			}
		}
		// 判断是否是第一层最后一个循环
		if (index !== attrs.length - 1) query += "&";
		return query;
	}, "");
}

export function showModal(
	options: {
		title?: string;
		content?: string;
		showCancel?: boolean;
		cancelText?: string;
		cancelColor?: string;
		confirmText?: string;
		confirmColor?: string;
		editable?: boolean;
		placeholderText?: string;
	} = {}
): Promise<boolean> {
	return new Promise((resolve, reject) => {

		const baseOption = {
			title: `提示`,
			showCancel: true,
			confirmColor: `#f37000`
		}
		options = { ...baseOption, ...options }

		uni.showModal({
			...options,
			success: function (res) {
				if (res.confirm) {
					resolve(true)
				} else if (res.cancel) {
					resolve(false)
				}
			},
			fail: () => {
				reject();
			}
		});
	})
}
export function showToast(
	title: string,
	icon: 'success' | 'loading' | 'none' | 'error' | undefined = 'success',
	mask: boolean | undefined = false,
	duration: number | undefined = 1500
): Promise<false | true> {
	return new Promise((resolve) => {
		let assertIcon = (icon as 'success' | 'loading' | 'none')
		const config: UniApp.ShowToastOptions = {
			title, icon: assertIcon, mask,
			duration,
			success: () => resolve(true),
			fail: () => resolve(false)
		}
		if (icon == 'error') {
			delete config.icon;
			config.image = '/static/images/wain.png'
		}
		uni.showToast(config);
	})
}


export function previewImage(options:{
	current:number|string;
	urls:Array<string>;
	indicator?:'default'|'number'|'none';
	loop?:boolean;
	longPressActions?:objectAny;
}){
	uni.previewImage({
		...options,
		longPressActions: {
			itemList: ['发送给朋友', '保存图片', '收藏'],
			success: function(data) {
				console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
			},
			fail: function(err) {
				console.log(err.errMsg);
			}
		}
	});
}


/**
 * 根据包裹类型状态获取 跑腿模块下的转换显示配置
 * 例如 最总显示 中物件 小物件
 * @param {0|1|2|3|4} status - 包裹类型状态 
 * @returns 
 */
export function togglePackStatus(
	status: number
) {
	const statusList = [{
		"text": "小物件",
		"value": 0,
		"color":"#f37000",
		"borderColor":"#f37000"
	},
	{
		"text": "中物件",
		"value": 1,
		"color":"#f37000",
		"borderColor":"#f37000"
	},
	{
		"text": "大物件",
		"value": 2,
		"color":"#f37000",
		"borderColor":"#f37000"
	},
	{
		"text": "超大物件",
		"value": 3,
		"color":"#f37000",
		"borderColor":"#f37000"
	},
	{
		"text": "急送",
		"value": 4,
		"color":"#f00",
		"borderColor":"#f00"
	}
	]

	const toggle = statusList.filter(it => it.value === status)
	return toggle[0]
}


export function toggleOrderStatus(status: number) {
	const statusList = [{
		"value": 0,
		"text": "待接单",
		"orderTitle":"等待骑手接单中",
		"orderTips":`您的订单已支付，等待骑手接单中`,
		"color":"#cb3800"
	}, {
		"value": 1,
		"text": "已接单",
		"orderTitle":"骑手已接单",
		"orderTips":`您的订单已被骑手接单，骑手正在取货中`,
		color:"#5055f4"
	}, {
		"value": 2,
		"text": "已取货",
		"orderTitle":"骑手已取货",
		"orderTips":`骑手已经取货，正在快马加鞭为你派送`,
		color:"#0090ff"
	}, {
		"value": 3,
		"text": "派送中",
		"orderTitle":"订单派送中",
		"orderTips":`骑手已经取货，正在快马加鞭为你派送`,
		color:"#f37000"
	}, {
		"value": 4,
		"text": "已完成",
		"orderTitle":"订单已完成",
		"orderTips":`感谢您对一统云校的信任，期待再次光临。`,
		color:"#149d1f"
	}, {
		"value": 5,
		"text": "已失败",
		"orderTitle":"订单已失败",
		"orderTips":`您的订单已失败，再来一单试试吧`,
		color:"#cb3800"
	}, {
		"value": 6,
		"text": "已取消",
		"orderTitle":"订单已取消",
		"orderTips":`您的订单已取消，期待再次光临`,
		color:"#757575"
	}, {
		"value": 7,
		"text": "已超时",
		"orderTitle":"订单已超时",
		"orderTips":`您的订单已配送超时，联系客服试试吧`,
		color:"#cb3800"
	}, {
		"value": 8,
		"text": "待付款",
		"orderTitle":"等待付款",
		"orderTips":`您的订单已创建，赶紧去付款吧`,
		color:"#757575"
	}, {
		"value": 9,
		"text": "退款/售后",
		"orderTitle":"订单已退款/售后",
		"orderTips":`异常订单，已为你择优处理`,
		color:"#757575"
	},{
		"value": 10,
		"text": "已取消",
		"orderTitle":"支付超时，订单已取消",
		"orderTips":`支付超时，订单已取消`,
		color:"#757575"
	}]


	const toggle = statusList.filter(it => it.value === status)
	return toggle[0]
}

export function baseCopy(str:string){
	uni.setClipboardData({
		data: str,
		success:  () =>{
			showToast(`复制成功`,`success`)
		},
		fail:()=>{
			showModal({
				title:`异常提示`,
				content:`复制失败请联系管理员`,
				showCancel:true
			})
		}
	});
}

export function timeOut(
	time:number|undefined=1000
):Promise<void>{
	return new Promise(resolve=>{
		setTimeout(()=>{
			resolve();
		},time)
	})
}

/**
 * 隐藏手机号码中间4位
 * @param {string} numberStr  - 11位手机号码
 */
export function hidePhoneNumber(numberStr:string):string{
	return numberStr.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}